package com.hello.sky.exception;

import com.hello.sky.constant.MessageConstant;
import com.hello.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(SkyException.class)
    public Result SkyExceptionHandler(SkyException e){
        String message = e.getErrorMessage();
        log.error("系统异常{}", message);
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result SQLIntegrityError(SQLIntegrityConstraintViolationException e){
        log.error("异常信息：{}", e.getMessage()); // Duplicate entry 'zhangsan' for key 'employee.idx_username'
        String message = e.getMessage();
        if (message.contains("Duplicate entry")) {
            return Result.error(message.split(" ")[2] + MessageConstant.ALREADY_EXISTS);
        }
        return Result.error(MessageConstant.UNKNOWN_ERROR);
    }
}
